package dev.loong.boot3.service.impl;

import dev.loong.boot3.dao.RoleDao;
import dev.loong.boot3.dao.UserDao;
import dev.loong.boot3.dao.UserRoleDao;
import dev.loong.boot3.pojo.User;
import dev.loong.boot3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class UserServiceImpl implements UserService{
    private UserDao userDao;
    private UserRoleDao userRoleDao;
    private RoleDao roleDao;
    @Autowired
    public UserServiceImpl(UserDao userDao,  UserRoleDao userRoleDao, RoleDao roleDao) {
        this.userDao = userDao;
        this.userRoleDao = userRoleDao;
        this.roleDao = roleDao;
    }
    @Override
    @Transactional
    @Cacheable(value = "redisCache", key = "'redis_user_'+#id")
    public User getUser(Long id) {
        return userDao.getUser(id);
    }

    @Override
    @Transactional
    @CachePut(value="redisCache", key="'redis_user_'+#result.id")
    public User insertUser(User user) {
        userDao.insertUser(user);
        return user;
    }

    @Override
    @Transactional
    @CacheEvict(value="redisCache", key="'redis_user_'+#id", beforeInvocation = false)
    public int deleteUser(Long id) {
        return userDao.deleteUser(id);
    }

    @Override
    @Transactional
    public List<User> findUsers(String userName, String note) {
        return userDao.findUsers(userName, note);
    }

    @Override
    @Transactional
    @CachePut(value = "redisCache", condition="#result != 'null'", key = "'redis_user_'+#id")
    public User updateUserName(Long id, String userName) {
        var user = getUser(id);
        if (user == null) {
            return null;
        }
        user.setUserName(userName);
        userDao.updateUser(user);
        return user;
    }

    @Override
    public int insert(User user) {
        return userDao.insertUser(user);
    }

    @Override
    public User getUserByName(String userName) {
        var user = userDao.getUserByName(userName);
        if (user == null) {
            return null;
        }
        var userRoles = userRoleDao.findUserRoles(user.getId());
        var roles = userRoles.stream().map(userRole -> roleDao.getRole(userRole.getRoleId())).toList();
        user.setRoles(roles);
        return user;
    }
}
